package com.fyzk.activity.lottery.shuzicai;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.LinearLayout;

import com.tyjc.lottery.R;
import com.fyzk.utils.ScreenUtils;
import com.fyzk.utils.SoundPoolUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 选球容器LinearLayout
 * 
 * @author fxs
 */
public class SelectBallLL extends LinearLayout {

	private Context context;
	/**
	 * 半径
	 */
	private float diameter;
	private float diameter_Max;
	private float diameter_Normal;

	private Bitmap[] bitmapRun = new Bitmap[3];
	/* 小球未选中状态的图片 */
	private static final int[] bitmapId = {R.drawable.dice_f1,R.drawable.dice_f2,R.drawable.dice_f3,R.drawable.dice_f4};
	private static final int[] bitmapId_checked = {R.drawable.dice1,R.drawable.dice2,R.drawable.dice3,
		R.drawable.dice4,R.drawable.dice5,R.drawable.dice6};
	private List<Bitmap> bitmaps = new ArrayList<Bitmap>();
	private List<Bitmap> bitmaps_checked = new ArrayList<Bitmap>();

	private Paint paint_ball;
	private Paint paint_txt;

	private int screen_width, screen_height, screen_DPI;
	private float screen_density;

	private String TAG = "SelectBallView";
	
	private Thread thread;
	float[] left = new float[3];
	float[] right = new float[3];
	float[] top = new float[3];
	float[] bottom = new float[3];
	int[] bitId_zhuan = new int[3];
	long time = 0;
	float offset = 0;
	private int[] lastX = new int[3];
	private int[] lastY = new int[3];
	private float[] offset_left = new float[3];
	private float[] offset_top = new float[3];
	
	float[] v_x = new float[]{10,10,10};
	float[] v_Y = new float[]{5,5,5};
	int[] direction_X = new int[]{1,1,1};
	int[] direction_Y = new int[]{1,1,1};
	
	boolean[] jiSuan = new boolean[]{true,true,true};
	int move_init_time = 10;
	boolean isMove = true;
	
	int move_lase_times = 10;
	float[] c_left = new float[3];
	float[] c_top = new float[3];
	
	int [] num = new int[3];
	
	public SelectBallLL(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		this.context = context;
		init();
		initAttrValue(attrs);
	}

	public SelectBallLL(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		this.context = context;
		init();
		initAttrValue(attrs);
	}

	public SelectBallLL(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.context = context;
		init();
	}

	private void initAttrValue(AttributeSet attrs) {
		TypedArray typedArray = context.obtainStyledAttributes(attrs,
				R.styleable.SelectBallView);
		int N = typedArray.getIndexCount();
		int resourceId;
		for (int i = 0; i < N; i++) {
			int attr = typedArray.getIndex(i);
			switch (attr) {
			case R.styleable.SelectBallView_ball_nor:
//				resourceId = typedArray.getResourceId(
//						R.styleable.SelectBallView_ball_nor, 0);
//				bitmap_ballnormal = BitmapFactory.decodeResource(
//						context.getResources(), resourceId);
				break;
			}
		}
		invalidate();
	}

	private void init() {
		setWillNotDraw(false);
		if(isInEditMode()){
			return;
		}
		// TODO Auto-generated method stub
		this.screen_width = ScreenUtils.getInstance().getWidth();
		this.screen_height = ScreenUtils.getInstance().getHeight();
		this.screen_DPI = ScreenUtils.getInstance().getDensityDPI();
		this.screen_density = ScreenUtils.getInstance().getDensity();
		
		diameter_Normal = (float) (screen_width / 6.0);
		diameter_Max = (float) (screen_width / 4.0);
		diameter = diameter_Normal;
		offset = (float) (screen_width / 3.0);
		
		for (int i = 0; i < bitmapId.length; i++) {
//			BitmapFactory.Options options = new BitmapFactory.Options();
//			options.inMutable = true;
//			options.inJustDecodeBounds = true;
			Bitmap btm = BitmapFactory.decodeResource(context.getResources(), bitmapId[i]);
			bitmaps.add(btm);
		}
		for (int i = 0; i < bitmapId_checked.length; i++) {
//			BitmapFactory.Options options = new BitmapFactory.Options();
//			options.inMutable = true;
//			options.inJustDecodeBounds = true;
			Bitmap btm = BitmapFactory.decodeResource(context.getResources(), bitmapId_checked[i]);
			bitmaps_checked.add(btm);
		}
		initPosition();
//		for (int i = 0; i < num.length; i++) {
//			Log.e(">>>>>>>>>>>>>init", i+" <init>:  left: "+left[i]+ " right: "+right[i] +
//					" top: "+top[i] + " bottom: "+bottom[i]);
//		}
		
//		this.getLocationOnScreen(location);
		
		setFocusable(true);
	}
	
	private void initValue(){
		time = 0;
		setInit(offset_left, 0);
		setInit(offset_top, 0);
		setInit(v_x, 10);
		setInit(v_Y, 5);
		setInit(jiSuan, true);
		isMove = true;
		move_lase_times = 10;
		setInit(c_left, 0);
		setInit(c_top, 0);
		
		offset = screen_width / 3;
		direction_X = new int[]{1,1,1};
		direction_Y = new int[]{1,1,1};
		
		diameter = diameter_Normal;
		waitTime = 0;
	}
	
	private void setInit(float[] arr, float initValue){
		for (int i = 0; i < arr.length; i++) {
			arr[i] = initValue;
		}
	}
	
	private void setInit(int[] arr, int initValue){
		for (int i = 0; i < arr.length; i++) {
			arr[i] = initValue;
		}
	}
	private void setInit(long[] arr, int initValue){
		for (int i = 0; i < arr.length; i++) {
			arr[i] = initValue;
		}
	}
	private void setInit(boolean[] arr, boolean initValue){
		for (int i = 0; i < arr.length; i++) {
			arr[i] = initValue;
		}
	}
	
	private static final int MESSAGE_ZHUAN = 0;
	private static final int MESSAGE_MOVE = 1;
	
	long waitTime = 0;
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MESSAGE_ZHUAN:
				time += 50;
				for (int i = 0; i < num.length; i++) {
					zhuan(i);
				}
				break;
			case MESSAGE_MOVE:
				waitTime+=100;
				for (int i = 0; i < num.length; i++) {
					if (isMove) {
						move(i);
						amplify();
					}else{
						if (waitTime >= 1000) {
							scale(i);
						}
					}
				}
				break;
			default:
				break;
			}
			invalidate();
		};
	};
	
	Runnable runnable = new Runnable() {
		int sleepTime = 100;
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while(isStrat){
				try {
					if (time < 3000) {
						sleepTime = 50;
						handler.sendEmptyMessage(MESSAGE_ZHUAN);
					}else{
						SoundPoolUtils.getSoundPool().stopSound();
						sleepTime = 100;
						handler.sendEmptyMessage(MESSAGE_MOVE);
					}
					Thread.sleep(sleepTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};
	
	private void zhuan(int id){
		bitId_zhuan[id]++;
		
		if (bitId_zhuan[id] == bitmaps.size() - 1) {
			bitId_zhuan[id] = 0;
		}
		bitmapRun[id] = bitmaps.get(bitId_zhuan[id]);
		if (time == 50) {
			v_x[id] = (float) (Math.random() * 20 + 15);
			v_Y[id] = (float) (Math.random() * 20 + 15);
		}
		if (left[id] > (screen_width/2.0 + offset - diameter) || left[id] < (screen_width/2.0 - offset)) {
			direction_X[id] = - direction_X[id];
			v_x[id]++;
		}else{
			v_x[id]--;
			if (v_x[id] == 0) {
				direction_X[id] = - direction_X[id];
				v_x[id] = (float) (Math.random() * 20 + 15);
			}
		}
		offset_left[id] += v_x[id] * direction_X[id];
		
		
		if (top[id] > (screen_width/2.0 + offset - diameter) || top[id] < (screen_width/2.0 - offset)) {
			direction_Y[id] = - direction_Y[id];
			v_Y[id]++;
		}else{
			v_Y[id]--;
			if (v_Y[id] == 0) {
				direction_Y[id] = - direction_Y[id];
				v_Y[id] = (float) (Math.random() * 20 + 15);
			}
		}
		offset_top[id] += v_Y[id] * direction_Y[id];
		initPosition();
	}
	
	private void move(int id){
		if (jiSuan[id]) {
			v_x[id] = offset_left[id] / move_init_time;
			v_Y[id] = offset_top[id] / move_init_time;
			jiSuan[id] = false;
		}
		bitmapRun[id] = bitmaps_checked.get(num[id]);
		if (offset_left[id] > 0) {
			offset_left[id] -= Math.abs(v_x[id]);
		}else if (offset_left[id] < 0) {
			offset_left[id] += Math.abs(v_x[id]);
		}
		
		if (offset_top[id] > 0) {
			offset_top[id] -= Math.abs(v_Y[id]);
		}else if (offset_top[id] < 0) {
			offset_top[id] += Math.abs(v_Y[id]);
		}
		initPosition();
		
	}
	
	private void amplify(){
		if (diameter < diameter_Max) {
			diameter += (diameter_Max - diameter_Normal) / move_init_time;
		}else{
			for (int i = 0; i < num.length; i++) {
				offset_left[i] = 0;
				offset_top[i] = 0;
				initPosition();
				c_left[i] = lastX[i] - left[i];
				c_top[i] = lastY[i] - top[i];
			}
			isMove = false;
		}
		initPosition();
		if (!isMove) {
			for (int i = 0; i < num.length; i++) {
				Log.e(">>>>>>>>>>>>>waitting", i+" <waitting>:  left: "+(int)left[i]+ " right: "+(int)right[i] + 
						" top: "+(int)top[i] + " bottom: "+(int)bottom[i]);
				Log.e(">>>>>>>>>>>>>waitting2", i+" <waitting2>:  off_left: "+(int)offset_left[i] +" off_top: "+(int)offset_top[i]);
			}
		}
	}
	
	private void scale(int id){
		offset_left[id] += (c_left[id] - (diameter_Max-diameter_Normal)*3/2) / move_lase_times;
		offset_top[id] += (c_top[id] - (diameter_Max-diameter_Normal)*3/2) / move_lase_times;
		if (id == 0) {
			diameter -= diameter_Max/move_lase_times;
		}
		
		if (diameter <= 0) {
			isStrat = false;
			moveStop();
			Log.e("<><><><><><><>end", id+" <end>:  left: "+(int)left[id]+ " right: "+(int)right[id] + 
					" top: "+(int)top[id] + " bottom: "+(int)bottom[id]);
			if (listener != null) {
				listener.random();
			}
		}
		initPosition();
	}
	
	public void setLastX(int[] lastX){
		this.lastX = lastX;
	}
	public void setLastY(int[] lastY){
		this.lastY = lastY;
	}
	float margin = 0;
	private void initPosition(){
		margin = diameter;
		if (diameter != diameter_Normal) {
			margin = diameter_Normal;
		}
		left[0] = (float) (screen_width/2.0 - diameter/2.0  + offset_left[0] - margin);
		right[0] = left[0] + diameter;
		top[0] = (float) (screen_width/2.0 - diameter/2.0 + offset_top[0] - margin);
		bottom[0] = top[0] + diameter;
		
		left[1] = (float) (screen_width/2.0 - diameter/2.0  + offset_left[1] + margin);
		right[1] = left[1] + diameter;
		top[1] = (float) (screen_width/2.0 - diameter/2.0 + offset_top[1] - margin);
		bottom[1] = top[1] + diameter;
		
		left[2] = (float) (screen_width/2.0 - diameter/2.0  + offset_left[2]);
		right[2] = left[2] + diameter;
		top[2] = (float) (screen_width/2.0 - diameter/2.0 + offset_top[2] + diameter_Normal);
		bottom[2] = top[2] + diameter;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (paint_ball == null) {
			paint_ball = new Paint(Paint.ANTI_ALIAS_FLAG);
			paint_ball.setColor(Color.BLACK);
			paint_ball.setTextSize(16 * screen_density);
			paint_ball.setTextAlign(Align.CENTER);
		}

		if (paint_txt == null) {
			paint_txt = new Paint(Paint.ANTI_ALIAS_FLAG);
			paint_txt.setTextSize(16 * screen_density);
			paint_txt.setTextAlign(Align.CENTER);
			Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
			paint_txt.setTypeface(font);
		}

		// 画球
		for (int i = 0; i < num.length; i++) {
			
			Rect rect = new Rect((int)left[i], (int)top[i], (int)right[i], (int)bottom[i]);
			Rect rect2 = new Rect(lastX[i] - 4, lastY[i] - 4, lastX[i] + 4, lastY[i] + 4);
			if (isStrat) {
				try {
//				canvas.drawRect(rect_kuang, paint_ball);
//					canvas.drawRect(rect2, paint_ball);
					canvas.drawBitmap(bitmapRun[i], null, rect, paint_ball);
					drawText(canvas, paint_txt, "", rect);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	}

	private boolean isStrat;
	/**
	 * 触屏事件
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		return isStrat;
	}

	@Override
	public void invalidate() {
		// TODO Auto-generated method stub
		super.invalidate();
	}

	/**
	 * 绘制文字
	 * 
	 * @param paint
	 * @param text
	 * @param rect
	 */
	private void drawText(Canvas canvas, Paint paint, String text, Rect rect) {
		paint.setTextSize(20 * screen_density);
		FontMetrics fm = paint.getFontMetrics();
		int baseLine = (int) (rect.top
				+ (rect.bottom - rect.top - fm.bottom + fm.top) / 2 - fm.top);
		canvas.drawText(text, rect.centerX(), baseLine, paint);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int width = this.screen_width;
		int height = heightMeasureSpec;
		setMeasuredDimension(width, height);
	}
	
	public void moveStart(){
		if (isStrat) {
			
		}else{
			time = 0;
			isStrat = true;
			thread = new Thread(runnable);
			thread.setDaemon(true);
			thread.start();
			initValue();
			SoundPoolUtils.getSoundPool().playSound(context, R.raw.k2_wheel, -1);
		}
	}
	
	public void moveStop(){
		
		if (this.thread != null) {
			Thread dummy = this.thread;
			this.thread = null;
			dummy.interrupt();
		}
	}
	
	public boolean isStarted(){
		return isStrat;
	}
	
	private RandomBallListener listener;
	public void setRandomBallListener(RandomBallListener listener){
		this.listener = listener;
	}
	public interface RandomBallListener {
		public void random();
	}
	
	public void setNumId(int [] num){
		this.num = num;
	}

}
